//
//  HomePlayerViewController.swift
//  FM
//
//  Created by x on 2017/9/26.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class HomePlayerViewController: UIViewController {
    
    /// 保存加出来的fm
    var models:[HomeFM]?
    
    /// 保存当前的正在播放的fm的下标
    var currentIndex:Int?
    
    /// 保存当前正在播放的FM
    var currentFM:HomeFM?
    
    
    /// 重写初始化方法
    ///
    /// - Parameters:
    ///   - data: <#data description#>
    ///   - index: <#index description#>
    init(data:[HomeFM], index:Int) {
        models = data
        currentIndex = index
        super.init(nibName: nil, bundle: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    /// 初始化
    func setupUI() -> Void {
        
        view.backgroundColor = UIColor.RGBColor(r: 211, g: 211, b: 211)
        
        //0.设置导航栏信息
        currentFM = models![currentIndex!]
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem(imageName: "back", target: self, action: #selector(backClick))
        navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName:UIColor.white]
        
        
        //1.添加子控件
        playerView.delegate = self
        view.addSubview(playerView)
        view.addSubview(commentTableView)
        
        //2.设置frame
        playerView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: playerView.playerViewHeight())
        commentTableView.frame = CGRect(x: 0, y: playerView.bounds.height, width: view.bounds.width, height: view.bounds.height-64-playerView.bounds.height)
        
        //3.设置播放界面的数据
        playerView.model = currentFM
        playerView.FMS = models
        
        //4.加载FM的评论数据
        loadCurrentFMComment(currentFM: currentFM!)
    }
    
    /// 加载当前FM的评论列表
    ///
    /// - Parameter currentFM: <#currentFM description#>
    fileprivate func loadCurrentFMComment(currentFM:HomeFM) -> Void {
        //4.加载FM的评论数据
        NetWorTools.shareNetWorkTools().loadFMDetailsInfoData(broadcast_id: currentFM.id!, offset: 0, successCallBack: { (data) in
            self.commentList = data
            self.commentTableView.reloadData()
        }) { (error) in
            print("loadFMDetailsInfoData=====",error)
        }
    }
    
    /// 加载更多评论数据
    func loadMoreCommonData() -> Void {
        
    }
    
    func backClick() -> Void {
        navigationController?.popViewController(animated: true)
    }
    
    //MARK: -- 懒加载
    
    private lazy var commentTableView:UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.backgroundColor = UIColor.clear
        //注册cell
        tableView.register(CommentCell.self, forCellReuseIdentifier: commentCellIdentifier)
        tableView.register(AnchorInfoCell.self, forCellReuseIdentifier: anchorInfoCellIdentifier)
        
        //给表哥添加上啦刷新
        tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreCommonData))
        
        return tableView
    }()
    
    fileprivate lazy var commentList:[Comment] = [Comment]()
    
    /// 保存cell的行高
    fileprivate lazy var rowHeightCaches:[String:CGFloat] = [String:CGFloat]()
    
    /// 加载播放View(相当于给个预估高度线布局 ,然后在设置真正的frame)
    private lazy var playerView:PlayerView = PlayerView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 300))
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

/// 主播介绍cell标识
private let anchorInfoCellIdentifier = "anchorInfoCellIdentifier"

/// 评论cell标识
private let commentCellIdentifier = "commentCellIdentifier"

extension HomePlayerViewController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return commentList.count+1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: anchorInfoCellIdentifier) as! AnchorInfoCell
            cell.model = currentFM
            
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: commentCellIdentifier) as! CommentCell
            cell.comment = commentList[indexPath.row-1]
            
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 160
        }else {
            let model = commentList[indexPath.row-1]
            
            //1.从缓存中取出行高
            let height = rowHeightCaches[model.id!]
            
            //2.如果缓存中有则直接返回
            guard height == nil else {
                return height!
            }
            
            //3.缓存中没有
            let cell = tableView.dequeueReusableCell(withIdentifier: commentCellIdentifier) as! CommentCell

            //4.计算高度
            let rowHeight = cell.rowHeight(model: model)
            
            //5.把高度存在缓存中
            rowHeightCaches[model.id!] = rowHeight
            
            return rowHeight
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

extension HomePlayerViewController:updateFMDetailsInfoDelegate {
    func showCurrentFMDetailsInfo(model: HomeFM) {
        //0.更新当前播放的FM
        currentFM = model
        
        //1.更新标题
        navigationItem.title = model.title
        
        //2.加载评论和主播的信息
        loadCurrentFMComment(currentFM: currentFM!)
    }
}












